/* 
 * The MIT License
 *
 * Copyright 2014 Venkat Ram Akkineni.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.netbeans.modules.tfsnb.core;

import com.microsoft.tfs.core.TFSConnection;
import com.microsoft.tfs.core.TFSTeamProjectCollection;
import com.microsoft.tfs.core.clients.framework.configuration.entities.ProjectCollectionEntity;
import com.microsoft.tfs.core.clients.framework.configuration.entities.TeamProjectEntity;
import com.microsoft.tfs.core.exceptions.TECoreException;
import com.microsoft.tfs.core.exceptions.TFSUnauthorizedException;
import com.microsoft.tfs.core.httpclient.Credentials;
import com.microsoft.tfs.core.httpclient.UsernamePasswordCredentials;
import com.microsoft.tfs.core.util.URIUtils;
import java.net.SocketException;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import org.openide.util.NbBundle;

import static org.netbeans.modules.tfsnb.core.ExceptionUtil.getRootException;
import org.openide.awt.NotificationDisplayer;
import org.openide.awt.StatusDisplayer;
import org.openide.util.ImageUtilities;

/**
 *
 * @author Venkat Ram Akkineni
 */
public class ConnectionService {
    
    private static final Logger LOG = Logger.getLogger(ConnectionService.class.getName());
    private static final String CONNECTION_ICON_URL = "org/netbeans/modules/tfsnb/core/TeamFoundationServer.gif";
    
    /**
     * 
     * @param cs
     * @return 
     */
    public boolean connect(final ConnectionSettings cs) {        
        Credentials credentials = new UsernamePasswordCredentials(cs.getUsername(), new String(cs.getPassword()));        
        TFSConnection connection = null;
        TFSTeamProjectCollection tfsTeamProjectCollection;
               
        tfsTeamProjectCollection = new TFSTeamProjectCollection(URIUtils.newURI(cs.buildFullUrl()), credentials);
        String message = "success";
        try {
            tfsTeamProjectCollection.authenticate();
            cs.setTeamProjectCollection(tfsTeamProjectCollection);
            return true;
        } catch(TFSUnauthorizedException e) {
            message = NbBundle.getMessage(ConnectionService.class, "ConnectionService.connectionFailed", e.getMessage());
            logAndNotify(message, cs.getName());                                   
            return false;
        } catch(TECoreException e) {
            Throwable root = getRootException(e);
            String reason = root.getClass().equals(SocketException.class) 
                    ? NbBundle.getMessage(ConnectionService.class, "ConnectionSettings.badProtocol", e.getMessage())
                    : e.getMessage();
            message = NbBundle.getMessage(ConnectionService.class, "ConnectionService.connectionFailed", reason);            
            logAndNotify(message, cs.getName());
            return false;
        }
    }
    
    /**
     * 
     * @param cs
     * @return 
     */
    public String testConnection(final ConnectionSettings cs) {
        Credentials credentials = new UsernamePasswordCredentials(cs.getUsername(), new String(cs.getPassword()));        
        TFSConnection connection = null;
        TFSTeamProjectCollection tfsTeamProjectCollection;
               
        tfsTeamProjectCollection = new TFSTeamProjectCollection(URIUtils.newURI(cs.buildFullUrl()), credentials);
        String message = NbBundle.getMessage(ConnectionService.class, "ConnectionService.success");
        try {
            tfsTeamProjectCollection.authenticate();
            tfsTeamProjectCollection.close();
        } catch(TFSUnauthorizedException e) {
            message = NbBundle.getMessage(ConnectionService.class, "ConnectionService.connectionFailed", e.getMessage());
            LOG.log(Level.INFO, message);            
        } catch(TECoreException e) {
            Throwable root = getRootException(e);
            String reason = root.getClass().equals(SocketException.class) 
                    ? NbBundle.getMessage(ConnectionService.class, "ConnectionSettings.badProtocol", e.getMessage())
                    : e.getMessage();
            message = NbBundle.getMessage(ConnectionService.class, "ConnectionService.connectionFailed", reason);            
            LOG.log(Level.INFO, message);            
        }
        return message;
    }
    
    /**
     * 
     * @param cs
     * @return 
     */
    public boolean disconnect(final ConnectionSettings cs) {
        if(isConnected(cs)) {
            try {
                cs.getTeamProjectCollection().close();
                cs.setTeamProjectCollection(null);
            } catch(final TECoreException e) {
                logAndNotify(NbBundle.getMessage(ConnectionService.class, "ConnectionService.connectionFailed"), cs.getName());
                return false;
            }
        }
        return true;
    }
    
    /**
     * 
     * @param cs 
     */
    public void add(final ConnectionSettings cs) {
        
    }
        
    /**
     * 
     * @param cs 
     */
    public void update(final ConnectionSettings cs) {
        
    }
    
    public void delete(final ConnectionSettings cs) {
        if(isConnected(cs)) {
            disconnect(cs);
        }
        TFSConnectionRegistry.getInstance().removeConnection(cs);
        String message = NbBundle.getMessage(TFSConnectionNode.class, "TFSConnectionNode.CTL_ConnectionDeletedNotificationMessage", cs.getName());
        logAndNotify(message, cs.getName());        
    }
    
    public ConnectionSettings[] retrieve() {
        Collection<ConnectionSettings> settingsCollection = TFSConnectionRegistry.getInstance().retrieveConnections().values();
        return settingsCollection.toArray(new ConnectionSettings[0]);
    }
    
    public boolean isConnected(final ConnectionSettings cs) {
        return cs.getTeamProjectCollection() != null && cs.getTeamProjectCollection().hasAuthenticated();        
    }
    
    public TFSTeamProjectCollection getTeamProjectCollection(final ConnectionSettings connectionSettings) {
        if(null == connectionSettings.getTeamProjectCollection()) {
            connect(connectionSettings);
        }
        return connectionSettings.getTeamProjectCollection();
    }
    
    /**
     * Just a utility method to log a message and show a notification bubble.
     * 
     * @param message
     * @param connectionName 
     */
    private void logAndNotify(final String message, final String connectionName) {
        LOG.log(Level.INFO, message); 
        StatusDisplayer.getDefault().setStatusText(message);
        NotificationDisplayer.getDefault().notify(connectionName,
                (Icon) ImageUtilities.loadImage(CONNECTION_ICON_URL),
                message, null, NotificationDisplayer.Priority.NORMAL);
    }

    public void mapWorkspaces(ConnectionSettings connectionSettings) {
        TFSTeamProjectCollection tfsTPT = connectionSettings.getTeamProjectCollection();
        ProjectCollectionEntity[] pce = tfsTPT.getConfigurationServer().getTeamFoundationServerEntity(true).getProjectCollections();
        for(int i = 0; i < pce.length; i++) {
            System.out.println(pce[i].getDisplayName());
        }
        
        TeamProjectEntity[] tp = tfsTPT.getTeamProjectCollectionEntity(true).getTeamProjects();
        for(int j = 0; j < tp.length; j++) {
            System.out.println(tp[j].getProjectName());            
        }
    }    
    
}
